package com.itheima.interceptor;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

public class MyInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //获取会话域中的数据
        Object user = request.getSession().getAttribute("user");
        if(user==null){
            Map<String,String> map=new HashMap<>();
            map.put("error","你还未登录,无权访问");
            //使用json将map集合响应给客户端
            response.setContentType("application/json;charset=utf-8");
            ObjectMapper objectMapper = new ObjectMapper();
            objectMapper.writeValue(response.getOutputStream(),map);
            return false;
        }
        return true;
    }
}
